import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnChanges
} from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { Router } from "@angular/router";
import { HttpServcie } from "../../../../service/http.service";
import { Config } from "../../../../service/config";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from "@angular/forms";
import { PartyBean } from "../bean/party.bean";
import { observable } from "rxjs/symbol/observable";

@Component({
  selector: "party-modify-page",
  templateUrl: "party-modify.html",
  styleUrls: ["party-modify.scss"]
})
export class PartyModifyPage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  functions: any = [];
  @Input() inValue: any = [];
  @Input('looktype') looktype: any = false;
  @Output("outPut") outPut = new EventEmitter();
  //系统类型
  partyTypeList: any = Config.PARTY_TYPE;
  companyBean: PartyBean = new PartyBean();
  //省市区
  options: any = [];
  //地址
  addresOptions: any = [];
  config: any = Config;
  parentList: any = [];
  startList = [
    { value: "二星", label: "二星" },
    { value: "三星", label: "三星" },
    { value: "四星", label: "四星" },
    { value: "五星", label: "五星" }
  ];
  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService
  ) {

    this.companyBean.id = JSON.parse(window.localStorage.getItem("user")).partyId;
    this.companyBean.parentId = JSON.parse(window.localStorage.getItem("user")).partyParentId;
    this.httpServcie
      .queryListStrParty({ parentId:this.companyBean.parentId,id: this.companyBean.id, partyType: "4", currentPage: 1, pageSize: 99999 })
      .subscribe(data => {
        console.log(data.data.list);
        this.parentList = data.data.list;
      });
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      addresOptions: [null, [Validators.nullValidator]], //行政区划
      partyName: [null, [Validators.required]], //单位名称
      partyAddr: [null, [Validators.nullValidator]], //单位地址
      corporation: [null, [Validators.nullValidator]], //法人代表
      telephone: [null, [Validators.nullValidator]], //单位电话
      postalCode: [null, [Validators.required,this.zipCode]], //邮政编码
      creditCode: [null, [Validators.nullValidator]], //组织机构代码
      businessLicenseNum: [null, [Validators.nullValidator]], //营业执照注册号
      contacts: [null, [Validators.required]],//联系人
      industry: [null, [Validators.nullValidator]], //所属行业
      contactsWork: [null, [Validators.nullValidator]], //联系人职务
      contactsCard: [null, [Validators.required,this.cardNumberCheck]], //联系人身份证号
      contactsPhone: [null, [Validators.required,this.fixIphoneCheck]], //联系人电话
      contactsEmile: [null, [Validators.required,this.emailCheck]], //联系人邮箱
      contactsMobile: [null, [Validators.required,this.mobileCheck]], //联系人手机
      contactsAddress: [null, [Validators.nullValidator]], //联系人地址
      parentId: [null, Validators.required],
      agree: [null, [Validators.nullValidator]],
      partyType: [null, [Validators.required]],
      zzdj: [null, [Validators.nullValidator]],
      maintStart: [null, [Validators.nullValidator]],
    });
  }


  // 身份证号码校验
  cardNumberCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if (!reg.test(control.value)) {
        return { checkFormat: true, error: true };
      }
    }
  };
  emailCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/;
      if (!reg.test(control.value)) {
        return { checkMobile: true, error: true };
      }
    }
  };
  /*邮政编码检验*/
  zipCode = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^[1-9][0-9]{5}$/;
      if (!reg.test(control.value)) {
        return { checkZipCode: true, error: true };
      }
    }
  };
  /*固定电话的检验*/
  fixIphoneCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
      if (!reg.test(control.value)) {
        return { fixIphoneCheck: true, error: true };
      }
    }
  };



  //手机号码校验
  mobileCheck = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value) {
      let reg = /^1[0-9]{10}$/;
      if (!reg.test(control.value)) {
        return { checkMobile: true, error: true };
      }
    }
  };

  ngOnChanges() {
    this.functions = [];
    if (this.inValue) {
      this.functions = this.inValue;
      this.httpServcie
        .partyQueryById({ id: this.inValue.id })
        .subscribe(data => {
          if (data.status == 200) {
            this.companyBean = data.data;
            let cityList: any = [];
            Config.CITY.forEach(element => {
              if (this.companyBean.partyProvince == element.value) {
                cityList.push(element);
              }
              if (this.companyBean.partyCity == element.value) {
                cityList.push(element);
              }
              if (this.companyBean.partyArea == element.value) {
                cityList.push(element);
              }
            });
            this.addresOptions = cityList;

            //图片回显
            if (this.companyBean.businessLicenseImg) {
              let list = this.companyBean.businessLicenseImg.split(",");
              let addList: any = [];
              list.forEach((element, index) => {
                let up: any = {};
                up["uid"] = index + "";
                up["url"] =
                  this.config.IP + this.config.API.getUpload + "/" + element;
                up["thumbUrl"] =
                  this.config.IP + this.config.API.getUpload + "/" + element;
                up["response"] = { data: element };
                addList.push(up);
              });
              this.fileList = addList;
            }

            if (this.companyBean.zzzs) {
              let list = this.companyBean.zzzs.split(",");
              let addList: any = [];
              list.forEach((element, index) => {
                let up: any = {};
                up["uid"] = index + "";
                up["url"] =
                  this.config.IP + this.config.API.getUpload + "/" + element;
                up["thumbUrl"] =
                  this.config.IP + this.config.API.getUpload + "/" + element;
                up["response"] = { data: element };
                addList.push(up);
              });
              this.zzzsList = addList;
            }
          }
        });
    }
  }

  submitForm($event, data) {
    //校验是否能提交
    //没有填的标红
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    //处理是否提交
    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }

    this.isSpinning = true;
    // 获取
    this.companyBean.loggerPartyId = JSON.parse(window.localStorage["user"]).partyId;

    this.companyBean.loggerType = JSON.parse(window.localStorage["user"]).partyType;


    if (this.addresOptions && this.addresOptions.length>0) {
      //省
      if (!this.addresOptions[0].value) {
        this.companyBean.partyProvince = this.addresOptions[0];
      } else {
        this.companyBean.partyProvince = this.addresOptions[0].value;
      }

      //市
      if (!this.addresOptions[1].value) {
        this.companyBean.partyCity = this.addresOptions[1];
      } else {
        this.companyBean.partyCity = this.addresOptions[1].value;
      }
      //区
      if (!this.addresOptions[2].value) {
        this.companyBean.partyArea = this.addresOptions[2];
      } else {
        this.companyBean.partyArea = this.addresOptions[2].value;
      }
    }
    //附件
    if (this.fileList.length > 0) {
      this.fileList.forEach(element => {
        this.companyBean.businessLicenseImg = element["response"]["data"];
      });
    }
    if (this.zzzsList.length > 0) {
      this.zzzsList.forEach(element => {
        this.companyBean.zzzs = element["response"]["data"];
      });
      if (!this.companyBean.zzdj) {
        this._notification.create("error", "失败提示", "请输入资质等级");
        this.isSpinning = false;
        return;
      }
    }
    if (this.companyBean.partyType != '1') {
      this.companyBean.maintStart = null;
    }
    let ob = this.httpServcie.partyUpdate(this.companyBean);
    ob.subscribe(data => {
      this.isSpinning = false;
      if (data.status == 200) {
        this._notification.create("success", "成功提示", "修改成功");
        this.outPut.emit($event);
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  //交验
  getFormControl2(name) {
    return this.validateForm.controls[name];
  }

  /** load data async  */
  loadData(e: {
    option: any;
    index: number;
    resolve: Function;
    reject: Function;
  }): void {
    if (e.index === -1) {
      e.resolve(this.httpServcie.getProvince());
      return;
    }

    const option = e.option;
    option.loading = true;
    if (e.index === 0) {
      let values: any = option["value"];
      let valueList = this.httpServcie.getCity(e.option);
      let cities: any = {};
      cities[values] = valueList;

      setTimeout(() => {
        option.loading = false;
        e.resolve(cities[option.value]);
      }, 1);
    }
    if (e.index === 1) {
      let value = option["value"];
      let valueList = this.httpServcie.getRelation(e.option);
      let scenicspots: any = {};
      scenicspots[value] = valueList;
      setTimeout(
        () => {
          option.loading = false;
          e.resolve(scenicspots[option.value]);
        },
        1,
        scenicspots,
        option
      );
    }
  }

  //文件上传
  previewImage = "";
  previewVisible = false;
  fileList: UploadFile[] = [];
  zzzsList: UploadFile[] = [];

  //查看
  handlePreview = (file: UploadFile) => {
    this.previewImage =
      this.config.IP +
      this.config.API.getUpload +
      "/" +
      file["response"]["data"] || file.thumbUrl;
    this.previewVisible = true;
  };

  //查看
  handlePreview2 = (file: UploadFile) => {
    this.previewImage =
      this.config.IP +
      this.config.API.getUpload +
      "/" +
      file["response"]["data"] || file.thumbUrl;
    this.previewVisible = true;
  };

  /**
   * 上传就开始调用
   * @param info
   */
  handleChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      this.fileList.forEach(element => {
        element["thumbUrl"] =
          this.config.IP +
          this.config.API.getUpload +
          "/" +
          element["response"]["data"];
      });
      // Get this url from response in real world.
    }
  }

  handleChange2(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      this.zzzsList.forEach(element => {
        element["thumbUrl"] =
          this.config.IP +
          this.config.API.getUpload +
          "/" +
          element["response"]["data"];
      });
      // Get this url from response in real world.
    }
  }

  //移除文件
  nzRemoveFile = (file: UploadFile) => {
    //移除fileList中的数据
    if (this.fileList.length == 1) {
      this.fileList = [];
      return;
    }
    let list: UploadFile[] = [];
    this.fileList.forEach((element, index) => {
      if (element["thumbUrl"] == file.thumbUrl) {
        this.fileList.splice(index, 1);
        this.fileList = this.fileList;
        list = this.fileList;
        this.fileList = [];
      }
    });
    list.forEach(element => {
      this.fileList.push(element);
    });
  };

  nzRemoveFile2 = (file: UploadFile) => {
    //移除fileList中的数据
    if (this.zzzsList.length == 1) {
      this.zzzsList = [];
      return;
    }
    let list: UploadFile[] = [];
    this.zzzsList.forEach((element, index) => {
      if (element["thumbUrl"] == file.thumbUrl) {
        this.zzzsList.splice(index, 1);
        this.zzzsList = this.zzzsList;
        list = this.zzzsList;
        this.zzzsList = [];
      }
    });
    list.forEach(element => {
      this.zzzsList.push(element);
    });
  };
}
